import { routerRedux } from 'dva/router';
import { Toast, Modal } from 'antd-mobile';
import * as authService from '../services/authService';

const delay = (time) => {
  return new Promise((rs) => {
    setTimeout(rs, time);
  });
};
export default {

  namespace: 'auth',

  state: {
    currentUser: {
      // _id: '593f9298e0f2f0e41358fa68',
      // shopId: 'qez_1111111',
      // branchNo: '0004',
      // salemanId: '33',
      // saleManName: 'aaaaa',
      // phone: '13666666666',
      profile: {
        // name: '',
        // avatar: '',
        // age: '',
        // gender: '',
      },
      roles: [],

    },
    btnText: '获取验证码',
    btnDisabled: false,
    saleman_list: [],
  },

  reducers: {
    loginSuccess(state, { payload: { shopId, branchId, saleManId, ...other } }) {
      const user = {
        shopId,
        branchNo: branchId,
        salemanId: saleManId,
        ...other,
      };

      return { ...state, currentUser: { ...state.currentUser, ...user } };
    },
    updateCountdown(state, { payload: { btnText, btnDisabled } }) {
      return {
        ...state,
        btnText,
        btnDisabled,
      };
    },
    getSalesmanSuccess(state, { payload }) {
      return {
        ...state,
        saleman_list: payload,
      };
    },
    updateAvatar(state, { payload: { avatar } }) {
      _.set(state, 'currentUser.profile.avatar', avatar);
      return { ...state };
    },
    getShopOpenidSuccess(state, { payload }) {
      _.set(state, 'currentUser.shopOpenid', payload.shopOpenid);
      return { ...state };
    },
  },
  effects: {
    * fetch({ payload }, { call, put }) {
      yield put({ type: 'save' });
    },
    * login({ payload: { phone, password } }, { call, put, select }) {
      const openid = yield select(state => state.auth.currentUser.openid);
      const result = yield call(authService.login, phone, password, openid);
      if (_.get(result, 'data.status') === 1) {
        setTimeout(() => {
          Toast.fail('账号已禁用！', 2);
        }, 100);
        return;
      }
      yield put({ type: 'loginSuccess', payload: result.data });
      if (result) {
        yield put(routerRedux.push({
          pathname: '/',
        }));
      }
    },
    * logout({ payload }, { call, put }) {
      Toast.loading('准备退出...');
      const result = yield call(authService.logout);
      yield put(routerRedux.replace({
        pathname: '/',
      }));
      location.reload();
    },
    * resetPassword({ payload: { oldPassword, password, confirmPassword } }, { call, put, select }) {
      const id = yield select(state => state.auth.currentUser._id);
      const result = yield call(
        authService.resetPassword,
        id, oldPassword, password, confirmPassword);
      if (result) {
        Toast.success('密码修改成功', 1);
        yield delay(1000);
        yield put(routerRedux.goBack());
      }
    },

    * findPassword({
                     payload: { phone, code, password },
                   }, { put, call, select }) {
      try {
        const data = yield call(authService.findPassword, phone, code, password);
        yield put(routerRedux.push({
          pathname: '/login',
        }));
        setTimeout(() => {
          Toast.success('密码修改成功', 1);
        }, 1);
      } catch (e) {
        setTimeout(() => {
          Toast.success('密码修改失败', 1);
        }, 1);
      }
    },
    * sendCode({
                 payload: { phone },
               }, { put, call, select }) {
      try {
        const data = yield call(authService.getCode, phone);
        yield put({ type: 'startCountdown' });
        setTimeout(() => {
          Toast.success('验证码发送成功', 1);
        }, 1);
      } catch (e) {
        setTimeout(() => {
          Toast.fail('验证码发送失败', 1);
        }, 1);
      }
    },
    * startCountdown({}, { put, call, select }) {
      let countdown = 60;
      while (countdown >= 0) {
        const values = {};

        if (countdown == 0) {
          values.btnText = '获取验证码';
          values.btnDisabled = false;
        } else {
          values.btnText = `${countdown}`;
          values.btnDisabled = true;
        }
        countdown--;
        yield put({ type: 'updateCountdown', payload: values });
        yield delay(1000);
      }
    },
    * baidu({ payload: { pathname, query } }, { select }) {
      const currentUser = yield select(state => state.auth.currentUser);
      const { shopId, shopName, branchName, username, saleManName, roles } = currentUser;

      if (!shopId || _.isNil(pathname)) return;

      // 自定义标签  品牌/分店
      _hmt.push(['_setUserTag', '1730', `${shopName}/${branchName || ''}`]);

      // 品牌/分店/访客
      const user = () => {
        let temp = '';
        if (roles.includes('boss')) {
          temp += 'boss';
        }
        if (username) {
          temp += username;
        } else if (saleManName) {
          temp += saleManName;
        }
        return temp;
      };
      _hmt.push(['_setUserTag', '2002', `${shopName}/${branchName || ''}/${user()}`]);

      // 子目录
      if (pathname === '/p1') {
        _hmt.push(['_trackPageview', `/task/${query.taskType}`]);
      } else if (pathname == '/') {
        _hmt.push(['_trackPageview', query.selected]);
      } else {
        _hmt.push(['_trackPageview', pathname]);
      }

      /*    if (pathname === '/p1' || pathname === '/p6' || pathname === '/p5') {
        // return _hmt.push(['_trackPageview', `/${shopId}/task/${query.taskType}/${query.subType || ''}`]);
        return _hmt.push(['_trackPageview', `/${shopName}/${branchName}/${shopId}/task/${query.taskType}/${query.subType || ''}`]);
      }
      _hmt.push(['_trackPageview', `/${shopName}/${branchName}/${shopId}${pathname}`]);*/
    },
    * fetch_saleman_list({ payload }, { put, select }) {
      const { roles, shopId, branchNo, salemanId } = yield select(state => state.auth.currentUser);
      const params = _.includes(roles, 'manager') || (!salemanId) ? { shopId, branchNo } : { shopId, branchNo, salemanId };
      const list = yield authService.getSalesman(params);
      yield put({ type: 'getSalesmanSuccess', payload: list.data });
    },
    * updateShopOpenid({ payload }, { call, put, select }) {
      const user = yield select(state => state.auth.currentUser);
      yield call(authService.updateUser, user._id, {
        shopOpenid: payload.shopOpenid,
      });
      yield put({ type: 'getShopOpenidSuccess', payload: { shopOpenid: payload.shopOpenid } });
      yield put(routerRedux.go(-1));
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {

      });
    },
  },
};
